package com.link.base.base.image.service;

import com.link.base.base.image.dao.mybatis.mapper.AppImageMapper;
import com.link.base.base.image.model.Image;
import com.link.base.core.basic.util.YmlConstants;
import com.link.base.user.model.CoreUser;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.dao.siebel.mapper.BasicMapperSiebel;
import com.link.core.basic.service.BasicServiceException;
import com.link.core.basic.service.BasicServiceImpl;
import com.link.core.cllog.LCLogger;
import com.link.core.util.DateUtil;
import com.link.core.util.ImageUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.Date;

/**
 * appimage根据父Id更新头Id
 * @author: LiQun
 * @date: 2018/8/20
 */
@Component
public class AppImageServiceImpl extends BasicServiceImpl<Image> implements AppImageService {
    @Resource
    private AppImageMapper appImageMapper;

    @Override
    public void imageHeadIdUpdate(Image image) throws Exception {
        appImageMapper.imageHeadIdUpdate(image);
    }

    @Override
    public BasicMapper<Image> getBasicMapper() throws Exception {
        return appImageMapper;
    }

    @Override
    public BasicMapperSiebel<Image> getSiebelBasicMapper() throws Exception {

        return null;
    }

    /**
     * 单个附件上传
     * @return Image
     * @author Lizt
     * @date 2019/1/25
     */
    @Override
    public Image upload(MultipartFile multiFile, Image record) throws Exception {
        CoreUser user = UserUtil.getUser();
        String moduleType = record.getModule();
        if (StringUtils.isNull(moduleType)) {
            moduleType = "other";
        }
        //获取源文件的文件类型
        String originalFilename = multiFile.getOriginalFilename();
        String fileType = originalFilename.substring(originalFilename.lastIndexOf('.') + 1).toLowerCase();
        //设置文件名
        String fileName = user.getId() + DateUtil.dateToStr(new Date(), "yyyy-MM-dd") + "." + fileType;
        // 存放附件的根路径
        String path = YmlConstants.getPortalShareFileDir();
        // 文件存放路径
        String filePath = path + moduleType + "/" + fileName;
        // 目标文件夹路径
        String fileFolder = path  +  moduleType ;
        //文件相对路径
        String relativePath =  moduleType + "/" + fileName;

        try {
            File file_folder = new File(fileFolder);
            if (!file_folder.exists()) {
                boolean isCreateSuccess = file_folder.mkdirs();
                if (isCreateSuccess) {
                    LCLogger.info().withMessageKey("uploadAppfile")
                            .withMessage("Create folder【" + fileFolder + "】 Success").flush();
                } else {
                    LCLogger.error().withMessageKey("uploadAppfile")
                            .withMessage("Create folder 【" + fileFolder + "】 Failed");
                }
            }
            if (!file_folder.isDirectory()) {
                LCLogger.error().withMessageKey("uploadAppfile")
                        .withMessage(fileFolder + "is not a file directory!");
            } else if (!file_folder.canRead()) {
                // 如果路径不可读，报错
                LCLogger.error().withMessageKey("uploadAppfile")
                        .withMessage("this folder can't be read " + fileFolder);
            } else if (!file_folder.canWrite()) {
                // 如果路径不可写，报错
                LCLogger.error().withMessageKey("uploadAppfile")
                        .withMessage("this folder can't be write " + fileFolder);
            }
            File file = new File(filePath);
            if (file.exists()) {
                throw new BasicServiceException("文件已经存在，保存文件失败！");
            } else {
                multiFile.transferTo(new File(filePath));
            }
            record.setAttachmentName(fileName);
            File f = new File(filePath);
            if (f.exists() && f.isFile()) {
                record.setAttachmentSize(String.valueOf(f.length()));
            } else {
                record.setAttachmentSize("0");
            }
            record.setModule(moduleType);
            record.setUrl(relativePath);
            record.setAttachmentOriginal(originalFilename);
            record.setFileType(fileType);
            if (fileType.equals("jpg") || fileType.equals("png") || fileType.equals("bmp") || fileType.equals("jpeg") || fileType.equals("gif")) {
                try {
                    String fileLessRelatePath = ImageUtil.makeSmallImage(filePath, fileName, YmlConstants.getPortalShareFileDir(), moduleType);
                    String bigLessRelatePath = ImageUtil.makeBigSmallImage(filePath, fileName, YmlConstants.getPortalShareFileDir(), moduleType);
                    record.setSmallurl(fileLessRelatePath);
                    record.setBigurl(bigLessRelatePath);
                } catch (Exception e) {
                    LCLogger.withException(e);
                }
            }
//            insert(record);
        } catch (Exception e) {
            LCLogger.withException(e);
            return record;
        }
        return record;
    }

    /**
     * 项目系统反馈功能保存图片
     *
     * @author 李莹
     * @date 2019/12/24 06:23
     * @param entity 图片实体对象
     * @throws Exception
     */
    @Override
    public void insertOuterImage(Image entity) throws Exception {
        appImageMapper.insertOuterImage(entity);
    }
}
